#!/usr/anaconda/env python
# -*- coding: utf-8 -*-
# author: uestcwdh
# @Time: 2020/2/2 12:43
import streamlit as st
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
st.title('iris classification')

iris_dataset = load_iris()
@st.cache()
def split_data():
    x_tr, x_te, y_tr, y_te = train_test_split(
        iris_dataset['data'], iris_dataset['target'], random_state=0
    )
    return x_tr, x_te, y_tr, y_te


x_train, x_test, y_train, y_test = split_data()
if st.checkbox('Show training data'):
    x_train, _, _, _ = split_data()
    df_train = pd.DataFrame(x_train)
    df_train.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
    st.table(df_train)

if st.checkbox('Show testing data'):
    df_test = pd.DataFrame(x_test)
    df_test.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
    st.table(df_test)

methods = st.sidebar.selectbox(
    "choose methods",
    ['knn', 'default']
)
if methods == 'knn':
    st.subheader("use knn to classify iris(acc on testing data)")
    n = st.sidebar.slider('n', 1, 20, 3, 1)
    knn = KNeighborsClassifier(n_neighbors=n)
    knn.fit(x_train, y_train)
    st.write("Test set score: {:.2f}".format(knn.score(x_test, y_test)))
    st.subheader("use knn to classify iris(prediction on an example)")
    lst = []
    sl = st.sidebar.slider('sepal_length', 0.0, 10.0, 0.0, 0.1)
    sw = st.sidebar.slider('sepal_width', 0.0, 10.0, 0.0, 0.1)
    pl = st.sidebar.slider('petal_length', 0.0, 10.0, 0.0, 0.1)
    pw = st.sidebar.slider('petal_width', 0.0, 10.0, 0.0, 0.1)
    lst.append(sl)
    lst.append(sw)
    lst.append(pl)
    lst.append(pw)
    X_new = np.array([lst])
    test_frame = pd.DataFrame(X_new)
    test_frame.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width']
    st.write("test example: ", test_frame)
    if st.button('predict'):
        pre = knn.predict(X_new)
        st.write("Prediction: {}".format(iris_dataset['target_names'][pre]))
    else:
        pass


